package com.example.ks.servlet;

import com.example.ks.dao.impl.UserDaoImpl;
import com.example.ks.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 获取用户选择的角色（默认0为普通用户）
        int role = request.getParameter("role") != null ?
                Integer.parseInt(request.getParameter("role")) : 0;

        UserDaoImpl userDao = new UserDaoImpl();

        try {
            User user = userDao.findByUsername(username);

            if (user != null) {
                // 验证密码和角色
                if (password.equals(user.getPassword()) && user.getRole() == role) {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", user);
                    // 根据角色跳转不同页面
                    if (role == 1) {
                        response.sendRedirect("admin-index"); // 管理员页面
                    } else {
                        response.sendRedirect("user-index"); // 普通用户页面，使用新的Servlet
                    }
                } else {
                    request.setAttribute("error", "用户名/密码错误");
                    request.getRequestDispatcher("login-register.jsp").forward(request, response);
                }
            } else {
                request.setAttribute("error", "用户不存在");
                request.getRequestDispatcher("login-register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "登录失败：数据库错误");
            request.getRequestDispatcher("login-register.jsp").forward(request, response);
        }
    }
}